package com.lsh.oms.provider.service.status;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.dubbo.rpc.protocol.rest.support.ContentType;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lsh.base.common.json.JsonUtils;
import com.lsh.base.common.model.CommonResult;
import com.lsh.oms.api.model.es.OrderHeadForEs;
import com.lsh.oms.api.model.status.MisArrivalDto;
import com.lsh.oms.api.service.status.IBillPayAccountService;
import com.lsh.oms.core.constant.ReturnCode;
import com.lsh.oms.core.enums.*;
import com.lsh.oms.core.model.order.OrderShippingHeadWithBLOBs;
import com.lsh.oms.core.model.order.OrderSignHead;
import com.lsh.oms.core.proxy.service.EsProxy;
import com.lsh.oms.core.service.other.SignOrderService;
import com.lsh.oms.core.service.po.OmsTaskService;
import com.lsh.oms.core.service.tool.ToolService;
import com.lsh.oms.provider.service.BaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author peter
 */
@Service(protocol = "rest")
@Path("other")
@Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_XML})
@Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8})
public class BillPayAccountRestServiceImpl extends BaseService implements IBillPayAccountService {

    Logger logger = LoggerFactory.getLogger(BillPayAccountRestServiceImpl.class);

    @Autowired
    private SignOrderService signOrderService;

    @Autowired
    private EsProxy esProxy;

    @Autowired
    private OmsTaskService omsTaskService;


    @POST
    @Path("update/arrival")
    @Override
    public CommonResult<Object> updateArrivalStatus(MisArrivalDto dto) {

        dto.setVenderId(this.getVenderId());
        String logSign = "logSign:" + ToolService.getLogSign() + ",";
        long startTimeMs = System.currentTimeMillis();
        logger.info(logSign + " : 更新签收单到账状态入参 －－ " + JsonUtils.obj2Json(dto));
        CommonResult<Object> result = new CommonResult<>();
        JSONArray json = JSONObject.parseArray(dto.getReceiptOrderId());
        if (json.size() <= 0) {
            result.setCode(ReturnCode.REQUEST_PARAMS_IS_NULL);
            result.setData(false);
            result.setMessage("参数中参数不合法，请检验。");
            return result;
        }
        List<Long> codes = new ArrayList<>();
        try {
            for (Object obj : json) {
                Long code = Long.parseLong(obj.toString());
                codes.add(code);
            }
        } catch (Exception e) {
            logger.info(logSign + "本次操作转换单号异常，参数:" + JsonUtils.obj2Json(dto));
            result.setCode(ReturnCode.REQUEST_PARAMS_IS_NULL);
            result.setData(false);
            result.setMessage("请求中有单号不是数字，请检验。");
            return result;
        }
        List<OrderSignHead> dbHeads = signOrderService.getBatchSignHeadBySignCode(codes);

//        List<OrderSignHead> goWithoutTms = signOrderService.retrieveGoWithoutTms(codes);

        List<OrderSignHead> oshUpdateList = new ArrayList<>(json.size());
        for (OrderSignHead head : dbHeads) {
            OrderSignHead oshUpdate = new OrderSignHead();
            oshUpdate.setReceiptOrderId(head.getReceiptOrderId());
            int payType = dto.getPayType() == null ? head.getPayType() : dto.getPayType();
            logger.info("payType is " + payType);
            oshUpdate.setPayType(payType);
            oshUpdate.setStatus(SignStatus.ARRIVAL.getIndex());
            oshUpdate.setPayStatus(PayStatus.PAID.getValue());
            if (payType == PayChannel.MONEY.getIndex()) {
                BigDecimal money = head.getMoney();
                BigDecimal[] floorMoneyList = money.divideAndRemainder(BigDecimal.ONE);
                BigDecimal floorMoney = floorMoneyList[1];
                oshUpdate.setMoney(money.subtract(floorMoney));
                oshUpdate.setFloorMoney(floorMoney);

                JSONObject extObject = JSON.parseObject(head.getExt());
                JSONObject headInfo = extObject.getJSONObject("head_info");
                headInfo.put("floor_money", floorMoney.toString());
                headInfo.put("money", (money.subtract(floorMoney)).toString());
                extObject.put("head_info", headInfo);
                oshUpdate.setExt(extObject.toJSONString());
            }

            oshUpdate.setActivedAt((int) TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()));
            oshUpdate.setVenderId(head.getVenderId());
            oshUpdateList.add(oshUpdate);

        }
        int successCount;
        try {
            logger.info(logSign + "签收单更新db参数:" + JsonUtils.obj2Json(oshUpdateList));
            successCount = signOrderService.updateArrivalStatusBatch(oshUpdateList, logSign);
            logger.info(logSign + "签收单更新db返回:" + successCount);
            if (successCount > 0) {
                this.omsTaskService.add35Task(oshUpdateList);
            }
        } catch (Exception e) {
            logger.info(logSign + "签收单更新db失败");
            result.setCode(ReturnCode.REQUEST_FAIL);
            result.setData(false);
            result.setMessage("签收单更新db失败，请检验。");

            return result;
        }
        result.setCode(ReturnCode.REQUEST_SUCCESS);
        result.setData(true);
        result.setMessage("oms处理成功");

        esProxy.batchEditIndex(oshUpdateList, logSign);
        this.esDeal(dbHeads, logSign);

        return result;
    }

//    /**
//     * @param oshUpdateList
//     */
//    private void addTask(List<OrderSignHead> oshUpdateList) {
//
//        try {
//            for (OrderSignHead orderSignHead : oshUpdateList) {
//                OmsTask filter = new OmsTask();
//                filter.setRefCode(orderSignHead.getReceiptOrderId() + "");
//                filter.setTaskType(TaskType.RECEIPT_TO_ACCOUNT.getCode());
//                List<OmsTask> omsTasks = omsTaskService.getTasksByFilter(filter);
//
//                if (!CollectionUtils.isEmpty(omsTasks)) {
//                    logger.info("receipt_order_id select omsTasks size {} ", orderSignHead.getReceiptOrderId(), omsTasks.size());
//                    continue;
//                }
//
//                OmsTask omsTask = new OmsTask();
//                omsTask.setRefCode(orderSignHead.getReceiptOrderId() + "");
//                omsTask.setTaskType(TaskType.RECEIPT_TO_ACCOUNT.getCode());
//                omsTask.setVenderId(orderSignHead.getVenderId());
//                omsTaskService.add(omsTask);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//    }

//    /**
//     * @param codes
//     */
//    private void addTask2(List<Long> codes, Long venderId) {
//        try {
//
//            for (Long code : codes) {
//                OmsTask filter = new OmsTask();
//                filter.setRefCode(code + "");
//                filter.setTaskType(TaskType.RECEIPT_TO_ACCOUNT.getCode());
//                List<OmsTask> omsTasks = omsTaskService.getTasksByFilter(filter);
//
//                if (!CollectionUtils.isEmpty(omsTasks)) {
//                    logger.info("receipt_order_id select omsTasks size  {} ", code, omsTasks.size());
//                    return;
//                }
//
//                OmsTask omsTask = new OmsTask();
//                omsTask.setRefCode(code + "");
//                omsTask.setVenderId(venderId);
//                omsTask.setTaskType(TaskType.RECEIPT_TO_ACCOUNT.getCode());
//                omsTask.setContent(code + "");
//                omsTaskService.add(omsTask);
//            }
////
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//    }

    /**
     * @param dbHeads
     * @param logSign
     */
    private void esDeal(List<OrderSignHead> dbHeads, String logSign) {
        for (OrderSignHead head : dbHeads) {
            OrderShippingHeadWithBLOBs oshEs = new OrderShippingHeadWithBLOBs();
            oshEs.setOrderId(head.getOrderId());
            oshEs.setShippingOrderId(head.getShippingOrderId());
            oshEs.setStatus(ShippingStatus.DELIVERED.getIndex());
            logger.info(logSign + "ES入参修改发货是-- " + JsonUtils.obj2Json(oshEs));
            esProxy.editIndex(oshEs, logSign);
            OrderHeadForEs ohEs = new OrderHeadForEs();
            ohEs.setOrderCode(head.getOrderId());
            ohEs.setOrderStatus(OrderStatus.ORDER_SIGN.getIndex());
            logger.info(logSign + "ES入参修改订单是-- " + JsonUtils.obj2Json(ohEs));
            esProxy.editIndex(ohEs, logSign);
        }
    }

}
